package com.zscat.mallplus.email.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.zscat.mallplus.annotation.SysLog;
import com.zscat.mallplus.email.entity.CmsEmail;
import com.zscat.mallplus.email.service.ICmsEmailService;
import com.zscat.mallplus.sys.service.ISysEmailConfigService;
import com.zscat.mallplus.sys.vo.EmailVo;
import com.zscat.mallplus.ums.entity.UmsMember;
import com.zscat.mallplus.ums.service.IUmsMemberService;
import com.zscat.mallplus.util.StringUtils;
import com.zscat.mallplus.utils.CommonResult;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author mallplus
 * @date 2019-12-17
 * 分销审核
 */
@Slf4j
@RestController
@RequestMapping("/cmsEmail")
@Validated
public class CmsEmailController {

    @Resource
    private ICmsEmailService iCmsEmailService;
    @Resource
    private IUmsMemberService iUmsMemberService;

    @Resource
    private ISysEmailConfigService emailService;


    @SysLog(MODULE = "email", REMARK = "新建邮件")
    @ApiOperation("新建邮件")
    @PostMapping(value = "/mng/list/json")
    public Object mngList(@RequestBody Map<String, String> params) {
        String kw = params.get("kw");
        String pageNum = params.get("pageNum");
        String pageSize = params.get("pageSize");
        return mngList(kw, Integer.parseInt(pageNum), Integer.parseInt(pageSize));
    }


    @SysLog(MODULE = "email", REMARK = "后台 邮件列表")
    @ApiOperation("后台 邮件列表")
    @GetMapping(value = "/mng/list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "kw", value = "搜索关键词"),
            @ApiImplicitParam(name = "pageNum", value = "页码"),
            @ApiImplicitParam(name = "pageSize", value = "页大小"),
    })
    public Object mngList(@RequestParam(value = "kw", defaultValue = "") String kw,
                          @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                          @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        try {
            QueryWrapper<CmsEmail> queryWrapper = new QueryWrapper<>();
            if (Objects.nonNull(kw) && StringUtils.isNotBlank(kw)) {
                kw = "%" + kw.replace(" ", "") + "%";
                queryWrapper.like("email_title", kw)
                        .or().like("email_detail", kw);
            }

            queryWrapper.orderByDesc("gmt_create");
            return new CommonResult().success(iCmsEmailService.page(new Page<CmsEmail>(pageNum, pageSize), queryWrapper));
        } catch (Exception e) {
            log.error("后台 活动列表：%s", e.getMessage(), e);
        }
        return new CommonResult().failed();
    }


    @SysLog(MODULE = "email", REMARK = "查询邮件详情")
    @ApiOperation("查询邮件详情")
    @GetMapping(value = "/detail/{id:.+}")
    public Object detail(@PathVariable("id") @NotNull Integer id) {
        try {
            return new CommonResult().success(iCmsEmailService.getById(id));
        } catch (Exception e) {
            log.error("查询活动详情：%s", e.getMessage(), e);
        }
        return new CommonResult().failed();
    }

    @SysLog(MODULE = "email", REMARK = "新建邮件")
    @ApiOperation("新建邮件")
    @PostMapping(value = "/saveOrUpdate/json")
    public Object saveOrUpdate(@RequestBody Map<String, String> params) {
        String emailTitle = params.get("emailTitle");
        String emailDetail = params.get("emailDetail");
        String memberIds = params.get("memberIds");
        return saveOrUpdate(null, emailTitle, emailDetail, memberIds);
    }


    @SysLog(MODULE = "email", REMARK = "新建或者修改邮件")
    @ApiOperation("新建或者修改邮件")
    @PostMapping(value = "/saveOrUpdate")
    public Object saveOrUpdate(
            @RequestParam(value = "id", required = false) Long id,
            @RequestParam(value = "emailTitle") @NotBlank String emailTitle,
            @RequestParam(value = "emailDetail") @NotBlank String emailDetail,
//            @RequestParam(value = "tos") @NotBlank String tos,
            @RequestParam(value = "memberIds") @NotBlank String memberIds
    ) {

        List<String> list = Lists.newArrayList();
        List<String> hasEmailIds = Lists.newArrayList();

        // 邮箱列表
        Lists.newArrayList(memberIds.split(",")).forEach(s -> {
            Long memberId = Long.parseLong(s);
            UmsMember member = iUmsMemberService.getById(memberId);
            if (Objects.nonNull(member) && StringUtils.isNoneBlank(member.getEmail())) {
                list.add(member.getEmail());
                hasEmailIds.add(s);
            }
        });

        CmsEmail email = new CmsEmail();
        if (Objects.nonNull(id)) {
            email.setId(id);
        }
        email.setRemark(String.join(",",hasEmailIds));
        email.setEmailDetail(emailDetail);
        email.setEmailTitle(emailTitle);
        email.setMemberIds(memberIds);
        email.setTos(String.join(",",list));
        iCmsEmailService.save(email);

        EmailVo emailVo = new EmailVo();
        emailVo.setTos(list);
        emailVo.setSubject(emailTitle);
        emailVo.setContent(emailDetail);
        try {
            emailService.send(emailVo, emailService.getOne(new QueryWrapper<>()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new CommonResult().success(
                new HashMap<String,List<String>>(){{
                    put("hasEmailIds",hasEmailIds);
                    put("emails",list);
                }}
        );
    }

    @SysLog(MODULE = "email", REMARK = "删除邮件发送记录")
    @ApiOperation("删除邮件发送记录")
    @PostMapping(value = "/del/{id:.+}")
    public Object del(@PathVariable("id") @NotNull @Min(1) Long id) {
        CmsEmail email = iCmsEmailService.getById(id);

        try {
            if (Objects.nonNull(email)) {
                if (iCmsEmailService.removeById(email)) {
                    return new CommonResult().success(email);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new CommonResult().failed();
    }


}


